/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hvtt.web.controller;

import com.hvtt.web.connection.Command;
import com.hvtt.web.connection.WEBConnection;
import com.hvtt.web.connection.WEBParamCollection;
import com.hvtt.web.controllerUtils.UtilsController;
import com.hvtt.web.models.C_blog;
import com.hvtt.web.models.C_blog;
import com.hvtt.web.models.C_hinhanh_xe;
import com.hvtt.web.utilities.Utilities;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.component.fileupload.FileUpload;
import org.primefaces.context.RequestContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.UploadedFile;

/**
 *
 * @author Administrator
 */
@ManagedBean
@SessionScoped
public class C_BlogController  implements Serializable{
      private WEBConnection DAL=new WEBConnection();
      private UploadedFile file;
      
    private C_blog item =new C_blog();
    
    public C_blog getItem()
    {
        return item;
    }
    public void setItem(C_blog item)
    {
        this.item=item;
    }
    
    public List<C_blog> findAllBlog() throws SQLException
    {
        List<C_blog> lst= DAL.executeQuery("Select C_Blog.HinhAnh,C_Blog.ID,C_Blog.TieuDe,C_Blog.TomTat,C_Blog.NgayDang,C_Blog.TrangThai from C_Blog order by C_Blog.NgayDang desc",C_blog.class);
        return lst;        
    }
    
     private String validateFields() throws SQLException {
        String str="";
       
        if (StringUtils.isBlank(this.getItem().getTieuDe()))
        {
            str+="  + " + Utilities.getLanguages("TieuDe")+": " + Utilities.getLanguages("Require") + "<br/>";
        }
       
        if("".equals(str.trim()))
            return "";
        return "<b style='color:black;'>" + Utilities.getLanguages("AdMsg0010") + ":</b> <br/>" +  "<b style='color:red;'>" + str + "</b>";
    }
    
    
    
    public void btnSave_Click(ActionEvent event) throws IOException, SQLException {
       
        
//          this.getItem().setTieuDe(String.valueOf(
//                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("TieuDe")));
//          this.getItem().setTomTat(String.valueOf(
//                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("TomTat")));
//          this.getItem().setNoiDung(String.valueOf(
//                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("NoiDung")));
          
//          this.getItem().setTrangThai(Integer.parseInt(FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("TrangThai").trim()));
          this.getItem().setTrangThai(0);
           String result = this.validateFields();
      
            if (!result.isEmpty()) {
                FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Message Status",result);
                FacesContext.getCurrentInstance().addMessage(null, msg);
                RequestContext.getCurrentInstance().execute("update=\"growl\"");
                return;
            }
          try   
          {
              String FileName="";
              if(file!=null)
              {
                  FileName=Utilities.parseDateTime(new Date(), "dd_MM_yyyy_hh_mm_ss")+"_" + file.getFileName();
                    FileUtils.copyInputStreamToFile(file.getInputstream(), new File(Utilities.GetPathUserUploadFile()+  File.separator + "SystemLogImg"+ File.separator + FileName));
                    
                    if(!"".equals(this.item.getHinhAnh().trim()))
                    {
                        File file1 = new File(Utilities.GetPathUserUploadFile()+  File.separator + Sys_NguoiDungController.findUser().getUserID()+ File.separator + this.item.getHinhAnh());
                        file1.deleteOnExit();
                    }
              }
           
             if(!"".equals(FileName.trim()))
                 this.item.setHinhAnh(FileName);
            WEBParamCollection Params=new WEBParamCollection();
            Params.add("Save");
            Params.add(this.item.getID());
            Params.add(this.item.getTieuDe());
            Params.add(this.item.getHinhAnh());
            Params.add(this.item.getTomTat());
            Params.add(this.item.getNoiDung());
            Params.add(this.item.getNguoiDang());
            Params.add(this.item.getTrangThai());
            Params.add(this.item.getThuTu());
            DAL.executeUpdate("{call Proc_C_Blog_In_Up_Del(?,?,?,?,?,?,?,?,?)}", Command.sqlStoredProcedure, Params);
            
            this.item.resetAttribute();
            file=null;
            
            FacesContext.getCurrentInstance().getExternalContext().redirect("/Admin/c/blog.html");
          }
          catch(Exception ex)
          {
              throw  ex;
          }
    }
    
     public void btnDelete_Click(ActionEvent event) throws IOException, SQLException {
       
        
          this.getItem().setID(Long.valueOf(
                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("ID")));
         
          try   
          {
           
            
            WEBParamCollection Params=new WEBParamCollection();
            Params.add(this.item.getID());
            List<C_blog> lst= DAL.executeQuery("Select*from C_blog where C_blog.ID=?", Command.sqlText, Params,C_blog.class);
            if(lst!=null && lst.size()>0)
            {
                this.setItem(lst.get(0));
               
            }
            
            if(!"".equals(this.item.getHinhAnh().trim()))
            {
                File file1 = new File(Utilities.GetPathUserUploadFile()+  File.separator + Sys_NguoiDungController.findUser().getUserID()+ File.separator + this.item.getHinhAnh());
                file1.deleteOnExit();
            }
             WEBParamCollection Params1=new WEBParamCollection();
            Params1.add(this.item.getID());
            DAL.executeUpdate("Delete from C_Blog where C_Blog.ID=?", Command.sqlText, Params1);
            
            FacesContext.getCurrentInstance().getExternalContext().redirect("/Admin/c/blog.html");
            file=null;
            this.item.resetAttribute();
            
          }
          catch(Exception ex)
          {
              throw  ex;
          }
    }
    public void btnUpdate_Click(ActionEvent event) throws IOException, SQLException {
       
        
          this.getItem().setID(Long.valueOf(
                FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("ID")));
         
          try   
          {
            WEBParamCollection Params=new WEBParamCollection();
            Params.add(this.item.getID());
            List<C_blog> lst= DAL.executeQuery("Select*from C_blog where C_blog.ID=?", Command.sqlText, Params,C_blog.class);
            if(lst!=null && lst.size()>0)
            {
                this.setItem(lst.get(0));
                FacesContext.getCurrentInstance().getExternalContext().redirect("/Admin/c/blog/new.html");
            }
          }
          catch(Exception ex)
          {
              throw  ex;
          }
    }
    public void btnNew_Click(ActionEvent event) throws IOException, SQLException {
       
        
         this.item.resetAttribute();
          FacesContext.getCurrentInstance().getExternalContext().redirect("/Admin/c/blog/new.html");
    }
    public void btnChiTiet_Click() throws IOException, SQLException {
       
         this.getItem().setID(Long.parseLong(Utilities.getRequest().getParameter("id")));
         
         WEBParamCollection Params=new WEBParamCollection();
            Params.add(this.item.getID());
            List<C_blog> lst= DAL.executeQuery("Select*from C_blog where C_blog.ID=?", Command.sqlText, Params,C_blog.class);
            if(lst!=null && lst.size()>0)
            {
                this.setItem(lst.get(0));
                //FacesContext.getCurrentInstance().getExternalContext().redirect("/blogdetail.html");
            }
        
    }
    
    public String getFullPathHinhAnh(String hinhanh)
     {
         UtilsController u=new UtilsController();
         if("".equals(hinhanh.trim()))
         {
            return u.getGetURLUserUploadFile() +"/default.jpg";
         }
         else
         { 
            File file = new File(Utilities.GetPathUserUploadFile() + File.separator + "SystemLogImg" +  File.separator + hinhanh);
            if(file.exists())
                return u.getGetURLUserUploadFile()+"/SystemLogImg/" + hinhanh;
            return u.getGetURLUserUploadFile() +"/default.jpg";
         }
     }
    
    public void handleFileUpload(FileUploadEvent event) {
         file=event.getFile();
         this.item.setFileHinhAnh(new DefaultStreamedContent(new ByteArrayInputStream(event.getFile().getContents()),event.getFile().getContentType()));
    }
     
     
     
}
